/*
 * Copyright 2010 Eligio Colutta
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package com.google.code.p2pxmppclient.executers.amule;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.google.code.p2pxmppclient.executers.CommandExecuter;


/**
 * 
 * @author eliosh
 * @version $Rev$
 * @lastautorcommit $Author$
 * @lastdatecommit $Date$
 */
public class AmulecmdExecuter implements CommandExecuter {

	/* (non-Javadoc)
	 * @see org.amule.jabber.executers.CommandExecuter#executeCommand(java.lang.String)
	 */
	public String executeCommand(String parameters) throws Exception{
		String[] params = parameters.split(" ");
		AmulecmdResponseTranslator translator = getTranslator(params);
		return translator.translate(executeCLI(parameters));
	}
	
	private AmulecmdResponseTranslator getTranslator(String[] params){
		AmulecmdResponseTranslator translator= new GenericAmulecmdResponseTranslator();
		
		String command = params[0];
		
		if("set".equals(command)){
			
		}else if("exit".equals(command)){
			
		}else if("show".equals(command)){
			// show dl
			if("dl".equals(params[1])){
				translator = new ShowDlAmulecmdResponseTranslator();
			}else if("log".equals(params[1])){
				translator = new ShowLogAmulecmdResponseTranslator();
			}
		}
		return translator;
	}
	
	private String[] executeCLI(String parameters) throws IOException{
		String s = "";
		String[] cmd = { "/bin/sh", "-c", "amulecmd -c '"+parameters+"'" };
		Process p = Runtime.getRuntime().exec(cmd);
        
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        ArrayList<String> res = new ArrayList<String>();

        // read the output from the command
        while ((s = stdInput.readLine()) != null) {
            res.add(s);
        }
        // remove first 4 lines (meaningful lines)
        List<String> test= res.subList(4, res.size());
        
		String[] retVal = new String[test.size()];
		test.toArray(retVal);
		return retVal;
	}
}
